<?php
// +-----------------+--------------+------+-----+---------+----------------+
// | Field           | Type         | Null | Key | Default | Extra          |
// +-----------------+--------------+------+-----+---------+----------------+
// | id              | int(11)      | NO   | PRI | NULL    | auto_increment |
// | name            | varchar(50)  | YES  |     |         |                |
// | title           | varchar(255) | YES  |     |         |                |
// | sort_num        | int(11)      | YES  |     | 0       |                |
// | seo_title       | varchar(255) | YES  |     |         |                |
// | seo_keywords    | varchar(255) | YES  |     |         |                |
// | seo_description | varchar(255) | YES  |     |         |                |
// | description     | varchar(255) | YES  |     |         |                |
// | content         | text         | YES  |     | NULL    |                |
// | pc_cover_id     | int(11)      | YES  |     | 0       |                |
// | wap_cover_id    | int(11)      | YES  |     | 0       |                |
// | status          | tinyint(1)   | YES  |     | 0       |                |
// | user_id         | int(11)      | YES  |     | 0       |                |
// | create_time     | int(11)      | YES  |     | 0       |                |
// | update_time     | int(11)      | YES  |     | 0       |                |
// +-----------------+--------------+------+-----+---------+----------------+
namespace app\common\model;
use think\Loader;
use think\Config;
use think\Db;
use app\common\model\Tag;
class Topics extends Base{
  protected $auto = ['user_id'];

  public function createOrUpdate($data){
    $res = ["status" => false, "msg" => "专题保存失败"];

    $user = login_user();
    if(empty($user)){
      $res["msg"] = "编辑用户不存在";
      return $res;
    }else if($user["user_type"] != "manager"){
      $res["msg"] = "您没有权限编辑该专题";
      return $res;
    }

    $validate = Loader::validate("Topics");
    if($validate->check($data)){
      $this->allowField(true);
      if(empty($data["id"])){
        $this->save($data);
        $id = $this->id;
      }else{
        $this->isUpdate(true)->save($data);
        $id = $data["id"];
      }
      $res = ["status" => true, "msg" => "专题保存成功"];
    }else{
      $res["msg"] = $validate->getError();
    }
    return $res;
  }

  /**
   * 关联查询单条记录详细信息
   * @Author zhanghong
   * @Date   2017-02-22
   * @param  [type]     $id          [description]
   * @param  boolean    $only_active 是否只显示status=1的记录
   * @return [type]                  [description]
   */
  public function relatedRead($id, $only_active = true){
    $prefix = Config::get("database.prefix");
    $this->join("{$prefix}user", "{$prefix}user.id={$prefix}article.user_id", "LEFT")
         ->join("{$prefix}upload wap_upload", "{$prefix}article.wap_cover_id={$prefix}upload.id", "LEFT");

    $select_fields = ["{$prefix}article.*"];
    array_push($select_fields, "{$prefix}user.nickname AS user_nickname");
    array_push($select_fields, "{$prefix}user.avatar AS user_avatar");
    array_push($select_fields, "{$prefix}user.description AS user_description");
    array_push($select_fields, "wap_upload.save_path AS wap_cover_path");
    $this->field($select_fields);

    $this->where("{$prefix}article.id", $id);
    $login_manager_id = login_manager_id();
    echo("login manager id: {$login_manager_id}");
    if($login_manager_id > 0){
      // 不需要指定任何参数
    }else if($only_active){
      //只能查看status=1或user_id=login_user_id（当前用户ID）的记录
      $user_id = login_user_id();
      $this->where("{$prefix}article.status=true OR {$prefix}article.user_id={$user_id}");
    }
    $item = $this->find();

    return $item;
  }

  /**
   * 查询方法
   * @Author zhanghong
   * @Date   2017-01-20
   * @param  [array]      $param     查询参数
   * @param  integer      $page_rows 每页显示的记录数
   * @return \think\paginator\Collection 
   */
  public function managerSelect($param, $page_rows = 15){
    $prefix = Config::get("database.prefix");
    
    $select_fields = [];
    $article_fields = ["id", "name", "title", "update_time", "status"];
    foreach ($article_fields as $idx => $key) {
      array_push($select_fields, "{$prefix}topics.{$key}");
    }
    array_push($select_fields, "{$prefix}user.nickname AS user_nickname");
    array_push($select_fields, "{$prefix}user.avatar AS user_avatar");
    array_push($select_fields, "wap_upload.save_path AS wap_cover_path");

    $allow_param = array_merge($param, ["query_mode" => "manager"]);
    $this->searchWhere($allow_param)->field($select_fields)
         ->join("{$prefix}user", "{$prefix}user.id={$prefix}topics.user_id", "LEFT")
         ->join("{$prefix}upload wap_upload", "{$prefix}topics.wap_cover_id={$prefix}upload.id", "LEFT")
         ->group("{$prefix}topics.id")->order("{$prefix}topics.id DESC");

    $config["query"] = ["query" => $param];
    // 分页参数名是 page ，paginate方法内有获取到该值的方法
    $page = 1;
    if(isset($param["page"])){
      $page = intval($param["page"]);
    }
    $config["page"] = $page;
    $paginate = $this->paginate($page_rows, false, $config);
    // $sql = $this->getLastSql();
    // echo($sql);
    return $paginate;
  }

  /**
   * 前台用户查询方法
   * @Author zhanghong
   * @Date   2017-02-15
   * @param  [array]      $param     查询参数
   * @param  integer      $page_rows 每页显示的记录数
   * @return \think\paginator\Collection 
   */
  public function memberSelect($param, $page_rows = 15){
    $prefix = Config::get("database.prefix");

    $select_fields = [];
    $article_fields = ["id", "name", "title", "description", "update_time", "create_time", "status", "user_id"];
    foreach ($article_fields as $idx => $key) {
      array_push($select_fields, "{$prefix}topics.{$key}");
    }
    array_push($select_fields, "{$prefix}user.nickname AS user_nickname");
    array_push($select_fields, "{$prefix}user.avatar AS user_avatar");
    array_push($select_fields, "wap_upload.save_path AS wap_cover_path");

    // 过滤掉不允许前台用户查询的字段
    $allow_param_names = array("keyword");
    foreach ($allow_param_names as $name) {
      if(isset($param[$name]) && !empty($param[$name])){
        $allow_param[$name] = $param[$name];
      }
    }
    $allow_param["query_mode"] = "member";

    $this->searchWhere($param)->field($select_fields)
         ->join("{$prefix}user", "{$prefix}user.id={$prefix}topics.user_id", "LEFT")
         ->join("{$prefix}upload wap_upload", "{$prefix}topics.wap_cover_id={$prefix}upload.id", "LEFT")
         ->group("{$prefix}topics.id")->order("{$prefix}topics.id DESC");

    $config["query"] = ["query" => $param];
    // 分页参数名是 page ，paginate方法内有获取到该值的方法
    $page = 1;
    if(isset($param["page"])){
      $page = intval($param["page"]);
    }
    $config["page"] = $page;
    $paginate = $this->paginate($page_rows, false, $config);
    // $sql = $this->getLastSql();
    // echo($sql);
    return $paginate;
  }

  /**
   * 生成搜索条件
   * @Author zhanghong
   * @Date   2017-04-12
   * @param    array      $param 请求参数
   * @return   array             Select Map
   */
  private function searchWhere($param){
    $prefix = Config::get("database.prefix");
    foreach ($param as $key => $value) {
      if(empty($value)){
        continue;
      }
      switch ($key) {
      case "keyword":
        if(empty($value)){
          continue;
        }else{
          $keyword = "%{$value}%";
        }
        $this->where("{$prefix}topics.title", "like", $keyword);
        break;
      }
    }

    if(!isset($param["query_mode"])){
      $param["query_mode"] = "member";
    }
    if($param["query_mode"] != "manager"){
      // 非个人用户并且不是管理员，只列表所有status=true的
      $this->where("{$prefix}topics.status", true);
    }
    return $this;
  }
}